package com.freedom.monitor.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.freedom.monitor.model.ServerId;
import com.freedom.monitor.model.Service;
import com.freedom.monitor.myeye.storage.service.ServerIdResult;
import com.freedom.monitor.myeye.storage.service.ServiceResult;
import com.freedom.monitor.myeye.storage.service.StorageService;
import com.freedom.monitor.myeye.storage.service.StorageService.Client;
import com.freedom.monitor.utils.ExclusionStrategyUtils;
import com.freedom.monitor.utils.StringUtils;
import com.freedom.rpc.thrift.common.utils.Logger;
import com.freedom.rpc.thrift.common.utils.SocketUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Controller
@RequestMapping(value = "/data")
public class DataController {

	// 这边都是从HBase查数据的
	private static final Logger logger = Logger.getLogger(DataController.class);

	// 首页进来
	@RequestMapping(value = "/index", method = { RequestMethod.GET })
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("index for data...");
		return new ModelAndView("data/index", model);// 返回data/index.jsp
	}

	// 查询某个产在HBase里都有哪些服务Key存在,以JSON数组形式返回
	@RequestMapping(value = "/service", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String service(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("DataController.service invoked...");
		try {
			String productCode = request.getParameter("productCode");
			if (false == StringUtils.valid(productCode)) {
				throw new Exception("invalid product code...");
			}
			logger.debug("begin to get StorageService.Client client");
			StorageService.Client client = (StorageService.Client) SocketUtils
					.getSyncAopObject(StorageService.Client.class);
			logger.debug("succeed to get StorageService.Client client ---> " + client);
			logger.debug("begin to invoke getService...");
			ServiceResult serviceResult = client.getService(productCode);
			logger.debug("succeed to invoke getService...");
			if (false == serviceResult.succeed) {
				throw new Exception(serviceResult.getErrorMsg());
			}
			if (serviceResult.getServiceList().isEmpty()) {
				throw new Exception("empty service from remote Storage service");
			}
			// 确实成功了&有效
			// 需要去根据编码查询mysql//TODO
			List<Service> serviceList = new ArrayList<Service>();
			for (String value : serviceResult.getServiceList()) {
				Service s = new Service();
				s.setSname(value);
				s.setScode(value);
				serviceList.add(s);
			}
			Gson gson = new GsonBuilder().setExclusionStrategies(ExclusionStrategyUtils.getInstance()).create();
			String str = gson.toJson(serviceList);
			logger.debug(str);
			return str;
		} catch (Exception e) {
			logger.error(e.toString());
			return "[]";// 返回空服务
		}

	}

	//////
	@RequestMapping(value = "/serverId", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String serverId(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("DataController.serverId invoked...");
		try {
			// 1)确保参数有效
			String productCode = request.getParameter("productCode");
			String serviceCode = request.getParameter("serviceCode");
			if (false == StringUtils.valid(productCode, serviceCode)) {
				throw new Exception("invalid product code/service code...");
			}
			// 2)尝试获取client
			logger.debug("begin to get StorageService.Client client");
			StorageService.Client client = (StorageService.Client) SocketUtils
					.getSyncAopObject(StorageService.Client.class);
			logger.debug("succeed to get StorageService.Client client ---> " + client);
			// 3)尝试调用服务
			logger.debug("begin to invoke getServerId...");
			ServerIdResult remoteResult = client.getServerId(productCode, serviceCode);
			logger.debug("succeed to invoke getServerId...");
			if (false == remoteResult.succeed) {
				throw new Exception(remoteResult.getErrorMsg());
			}
			if (remoteResult.getServerIdList().isEmpty()) {
				throw new Exception("empty serverId from remote Storage service");
			}
			// 确实成功了&有效
			List<ServerId> serverIdList = new ArrayList<ServerId>();
			for (String value : remoteResult.getServerIdList()) {
				ServerId s = new ServerId();
				s.setCode(value);
				s.setName(value);
				serverIdList.add(s);
			}
			Gson gson = new GsonBuilder().setExclusionStrategies(ExclusionStrategyUtils.getInstance()).create();
			String str = gson.toJson(serverIdList);
			logger.debug(str);
			return str;
		} catch (Exception e) {
			logger.error(e.toString());
			return "[]";// 返回空列表
		}
	}

}
